package com.kaifamiao.kfm.config.security;

import com.alibaba.fastjson.JSON;
import com.kaifamiao.kfm.util.Constants;
import com.kaifamiao.kfm.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 存认证信息
        redisTemplate.opsForValue().set(request.getSession().getId() + Constants.LOGIN_USER_KEY_SUFF, SecurityContextHolder.getContext().getAuthentication().getPrincipal());
//        request.getSession().setAttribute("user", SecurityContextHolder.getContext().getAuthentication());
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        String str = JSON.toJSONString(JsonResult.success("登录成功", "/index"));
        response.getWriter().print(str);
    }
}
